<?php
require_once( realpath( dirname( __FILE__ ) . '/../.apps/classes/tsActionBase.class.php' ) );

require_once( 'facebook/facebook.php' );
require_once( 'plugins/common/common_view.php' );
require_once( 'models/User.model.php' );
require_once( 'models/Liked.model.php' );
require_once( 'models/Shared.model.php' );
require_once( 'models/Watched.model.php' );
/**
 * Facebook Application for Youtube Video
 *
 * @author HUYHQ
 */
class tsActionFbYoutubeVideos extends tsActionBase
{
	//const MSG_NAME_NUM = 3;
    //const OUTPUT_EXT = ".png";

	private $facebook = null;
	private $sesskey = '';
	private $viewRemain= 0;
	private $watchedCount = 0;
	private  $likePage = FALSE;

	public function authorize()
    {
        // if app access scope is denied, redirect to the facebook canvas.
        //
        if( 'user_denied' == $this->get( 'error_reason' ) )
        {
            if( $canvas_url = $this->config( 'FACEBOOK', 'canvas' ) )
            {
                self::redirect4fb( $canvas_url );
            }
        }

        parent::authorize();
    }
	public function actionBefore(){
		//P3P compact policy
        //
        //header( 'P3P: CP="CAO PSA OUR"' );
        //header( 'P3P: CP="UNI CUR OUR"' );
        header( 'P3P: CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"' );

        // generate Facebook SDK instance
        //
        $fbconfig = array(
                         'appId'  => $this->config( 'FACEBOOK', 'appId' ),
                         'secret' => $this->config( 'FACEBOOK', 'secret' ),
                         );
        $this->facebook = new Facebook( $fbconfig );
        // set session key
        //


        $this->sesskey = md5( __CLASS__ );
	}
	public function action(){
		if( false === strpos( $_SERVER['HTTP_USER_AGENT'], 'facebookexternalhit' ) )
        {
            if( '1' != $this->get( 'fb' ) )
            {
                // TOPï¼ˆãƒšãƒ¼ã‚¸ã‚¢ãƒ—ãƒªï¼‰ã�‹ã‚‰ä»¥å¤–ã�®ã‚¢ã‚¯ã‚»ã‚¹ã�¯ã€�TOPã�«æˆ»ã�™
                //self::redirect4fb( $this->config( 'FACEBOOK', 'canvas' ) );
            }
        }
        /* user youtube
         * locbachkhoa		-> 26
         * 12345djbridger 	->608
         * thichngoinet 	->64
         */

		$youtubeUser = 'thichngoinet';
		$search = array('1'=>'published','2'=>'viewCount', '3'=>'rating');
		if(isset($_GET["sort"])){
			$searchType = $_GET["sort"];

		}else{
			$searchType = isset($_POST["sort"]) ? $_POST["sort"]:1;
		}
		$offset = isset($_GET["start-index"]) ? $_GET["start-index"]:1;
		$itemPerPage =  $this->config( 'VIDEOAPPS','itemPerPage');
		$params = array(
				'author'		=> $youtubeUser,
				'start-index'	=> $offset,
				'max-results'	=> $itemPerPage,
				'orderby'		=>$search[$searchType],
				'alt'			=>'json'
			);

		$options = array('searchType'=>$searchType);


		return $this->doVideos($params, $options);
	}
	public function doVideos($params = array(), $options = array()){
		//if(!isset($_POST['isLike']))
        //{
		$signed_request = @$this->facebook->getSignedRequest();
		$this->likePage = @$signed_request["page"]["liked"];

        //}
        /*else{
        	$this->likePage =$_POST['isLike']?TRUE:FALSE;
        }*/
		echo '<br />like = :';
		var_dump($this->likePage);

		//$options['isLike'] = $isLike;

		$userId = $this->facebook->getUser();

		$arrayVideos = array();
		$url = 'http://gdata.youtube.com/feeds/api/videos?'. $this->buildQuery($params);

		$videos =  common_view::getContentFromUrl('http://gdata.youtube.com/feeds/api/videos?'. $this->buildQuery($params));
		$videos = json_decode($videos);

		$summaryData = array(
							'summary' => array(
										'openSearchTotalResults'	=>$videos->feed->{'openSearch$totalResults'}->{'$t'},
										'openSearchStartIndex'		=>$videos->feed->{'openSearch$startIndex'}->{'$t'},
										'openSearchItemsPerPage'	=>$videos->feed->{'openSearch$itemsPerPage'}->{'$t'}));

		$totalRemain = $this->updateRemain($userId);

		if($totalRemain){
			foreach ($videos->feed->entry as $key => $item) {
				$arr = preg_split('/\//', $item->id->{'$t'});
				$videoId = $arr[count($arr)-1];
				foreach ( $item->{'media$group'}->{'media$thumbnail'} as $thumb) {
					$thumbnail = array(	'url'		=> $thumb->url,
										'height'	=> $thumb->height,
										'width'		=> $thumb->width
					);
				}

				$duration = $item->{'media$group'}->{'yt$duration'}->seconds;
				$duration = $duration<3600?gmdate("i:s", $duration):gmdate("H:i:s", $duration);
				/*if(isset($item->{'media$group'}->{'media$content'}[0]->duration)){
					$duration = ($item->{'media$group'}->{'media$content'}[0]->duration)<3600?gmdate("i:s", $item->{'media$group'}->{'media$content'}[0]->duration):gmdate("H:i:s", $item->{'media$group'}->{'media$content'}[0]->duration);
				}*/
				$playIcon = '<img src="/img/video_play_01.png " class="video-play cPoiter" onclick="playVideo(&#39;'. $videoId.'&#39;)"/>';
				$title = '<a href="#" class="video-name" onclick="playVideo(&#39;'. $videoId.'&#39;)">'.$item->title->{'$t'}.' </a>';
				$arrayVideos[] = array(
								'id'		=> $arr[count($arr)-1],
								'title'		=> $item->title->{'$t'},
								'titleLink'		=> $title,
								'player"'	=> $item->{'media$group'}->{'media$player'}[0]->url,
								'desc'		=> common_view::excerpt( $item->{'media$group'}->{'media$description'}->{'$t'}, 150, TRUE),
								'duration'	=> $duration,
								'playIcon'	=> $playIcon,
								'thumbnail'	=> $thumbnail,
								'viewCount'	=> $item->{'yt$statistics'}->viewCount,
								'published'	=> date('Y/m/d', strtotime($item->published->{'$t'})),
								'updated'	=> date('Y/m/d', strtotime($item->updated->{'$t'}))
				);
			}
		}else{// Total view remain = 0
			$watch = new Watched();
			foreach ($videos->feed->entry as $key => $item) {
					$arr = preg_split('/\//', $item->id->{'$t'});
					foreach ( $item->{'media$group'}->{'media$thumbnail'} as $thumb) {
						$thumbnail = array(	'url'		=> $thumb->url,
											'height'	=> $thumb->height,
											'width'		=> $thumb->width
						);
					}
					$duration = ($item->{'media$group'}->{'media$content'}[0]->duration)<3600?gmdate("i:s", $item->{'media$group'}->{'media$content'}[0]->duration):gmdate("H:i:s", $item->{'media$group'}->{'media$content'}[0]->duration);


					$videoId = $arr[count($arr)-1];
					$playIcon = '<img src="/img/video_play_01.png " class="video-play cPoiter" onclick="playVideo(&#39;'.$videoId.'&#39;)"/>';
					$title = '<a href="#" class="video-name" onclick="playVideo(&#39;'. $videoId.'&#39;)">'.$item->title->{'$t'}.' </a>';

					if(!$watch->checkWatched($videoId, $this->facebook->getUser()) ){
						$playIcon = '<img src="/img/video_lock_01.png" class="lock-play"/>';
						$title = '<a href="#" class="video-name cDefault"  rel1 = "{videoData.id}">'.$item->title->{'$t'}.' </a>';
					}


					$arrayVideos[] = array(
									'id'		=> $arr[count($arr)-1],
									'title'		=> $item->title->{'$t'},
									'titleLink'		=> $title,
									'player"'	=> $item->{'media$group'}->{'media$player'}[0]->url,
									'desc'		=> common_view::excerpt( $item->{'media$group'}->{'media$description'}->{'$t'}, 150, TRUE),
									'duration'	=> $duration,
									'playIcon'	=> $playIcon,
									'thumbnail'	=> $thumbnail,
									'viewCount'	=> $item->{'yt$statistics'}->viewCount,
									'published'	=> date('Y/m/d', strtotime($item->published->{'$t'})),
									'updated'	=> date('Y/m/d', strtotime($item->updated->{'$t'}))
					);
				}
		}

		return $this->viewVideos($arrayVideos, $summaryData, $options, $params);
	}

	public function viewVideos($arrayVideos = array(), $summaryData = array(), $options = array(), $params = array()){
		$tpl = $this->loadTemplate( 'videos.tpl' );
		$videoData = $arrayVideos;
		$tpl->setCurrentBlock( 'videoBlock' );
		//$tpl->setVariable('pageData', $option[0]);
		foreach ($videoData as $item) {
			$tpl->setVariable('videoData', $item);
			$tpl->parseCurrentBlock('videoBlock');
		}
		//$params = array();
		$curretPage =  isset($_GET['page'])? $_GET['page']:1;
		$params['sort'] = $options['searchType'];
		$paging = self::show_paging($summaryData['summary']['openSearchTotalResults'], $curretPage,'',TRUE,20,9,  '', $params) ;

		foreach ($paging  as $key=>$item) {
			$tpl->setVariable(array(
						'paging'=> $item));
			$tpl->parse('pagingBlock');
		}
		//Search option
		$search = array('1'=>'Publihed time','2'=>'View count', '3'=>'Rating');
		$searchOp = '';
		for ($i=1; $i<=3; $i++){
			$searchOp .= '<option value="'.$i.'" class="choose-list"  onclick="sort(this.value)" '.($options['searchType']==$i?'selected="selected"':'' ).'>'.$search[$i].'</option>';
		}

		//var_dump($option[0]);die;
		//$tpl->setVariable('pageData', 'hello');
		$tpl->setVariable( 'FB.appId', $this->config( 'FACEBOOK', 'appId' ) );
		$tpl->setVariable( 'viewRemain', $this->updateRemain($this->facebook->getUser()) );
		$tpl->setVariable( 'watchedCount', $this->updateWatchedCount($this->facebook->getUser()));
		$tpl->setVariable( 'searchOption', $searchOp);
		$tpl->setVariable( 'isLike', $this->likePage);

		$tpl->show();

	}

	public function doPlay(){
		$vId = $this->req->_requests['vid'];
		$videoData = array(
				'videoId'		=> $vId,
				'videoThumb'	=> $this->req->_requests['videoThumb_'.$vId],
				'videoTitle'	=> $this->req->_requests['videoTitle_'.$vId],
				'videoDesc'		=> $this->req->_requests['videoDesc_'.$vId]
		);
		$this->viewPlay($videoData);

	}

	public function viewPlay($videoData=array()){
		$tpl = $this->loadTemplate( 'play.tpl');

		//$tpl->setCurrentBlock('videoPlayer');
		foreach ($videoData as $key => $value) {
			$tpl->setVariable($key, $value);
		}
		//$tpl->setVariable('videoId', $videoData['videoId']);
		$tpl->setVariable( 'FB.appId', $this->config( 'FACEBOOK', 'appId' ) );

		$tpl->setVariable( 'viewRemain', $this->updateRemain($this->facebook->getUser()) );
		$tpl->setVariable( 'watchedCount', $this->updateWatchedCount($this->facebook->getUser()));
		$tpl->setVariable('redirect_uri', $this->config( 'FACEBOOK', 'redirect_uri' ) );
		//$tpl->parseCurrentBlock('videoPlayer');
		$tpl->show();
	}

	/**
	 *
	 * Enter description here ...
	 * @param  $option
	 * 	TRUE: update view remain
	 * 	FALSE: check and set like,share into LIKED, SHARED table
	 */
	public function doRemain($option = FALSE){
		$likeCount = 0;
		$like = new Liked();
		if($option){
			$this->viewRemain = $this->updateRemain($this->facebook->getUser());
			return;
		} else{
			$isLike = $videoId = $this->get('like');
			$videoId = $this->get('videoId');

			//Click share and share to wall
			if( $isLike==2 ){
				//Code
				$share = new Shared();
				if(!$share->checkShared( $videoId, $this->facebook->getUser())){
						$share->insertShared($videoId, $this->facebook->getUser(), $this->config( 'VIDEOAPPS','sharedIncrease'));
					}
			}else{//Click like
				if($isLike == 1){
					if(!$like->checkLiked( $videoId, $this->facebook->getUser())){
						$like->insertLike($videoId, $this->facebook->getUser(), $this->config( 'VIDEOAPPS','likedIncrease'));
					}
					else {
						$like->setLikeValue($videoId, $this->facebook->getUser(), 1);
					}
				}

				//Unlike
				else{
					$like->setLikeValue($videoId, $this->facebook->getUser(), 0);
				}
			}
			$totalViewRemain = $this->updateRemain($this->facebook->getUser());
			echo $totalViewRemain;
		}


		//$this->viewRemain( );
	}

	public function doWatch(){
		if(($this->get('videoId'))){
			$videoId = $this->get('videoId');
			$userId = $this->facebook->getUser();
			$watch = new Watched();

			if(!$watch->checkWatched($videoId,$userId )){
				$watch->insertWatched($videoId, $userId);
				$tableName = 'shared';
				$decreaseVideo = $watch->getDecreaseVideo($userId, $tableName);

				if($decreaseVideo == '' ){
					$tableName = 'liked';
					$decreaseVideo = $watch->getDecreaseVideo($userId, $tableName);
				}
				//Decrease in shared table
				$watch->updateCount($userId, $decreaseVideo, $tableName);
				$viewRemain = $this->updateRemain($userId);
			}
		}
		return $this->viewWatch();
	}

	public function viewWatch(){

		$tpl = $this->loadTemplate( 'watch.tpl');
		$tpl->setVariable( 'viewRemain', $this->updateRemain($this->facebook->getUser()) );
		$tpl->setVariable( 'watchedCount', $this->updateWatchedCount($this->facebook->getUser()));
		//$tpl->setVariable( 'love', 'love me' );
		$tpl->show();
	}

	public function updateRemain($userId = NULL){
		$likeCounter = 0;
		$shareCouter = 0;
		$like = new Liked();
		$share = new Shared();
		$shareCouter  = $share->shareCounter($userId);
		$likeCounter = $like->likeCounter($userId);
		return intval( $shareCouter)+ intval($likeCounter);
	}

	public function updateWatchedCount($userId = NULL){
		$watch = new Watched();
		return intval($watch->watchCouter($userId));
	}


	/*Paging function
	 *
	 * */
	static function show_paging($totalItem, $currentPage, $url, $showInfo = TRUE, $perPage = 20, $showPage = NULL,  $attr_arr = NULL, $condition_arr = array(), $pageParam = NULL) {
		$page = array();
		$query = '';
		$totalPage = ceil($totalItem / $perPage);

		$currentPage = $currentPage?$currentPage:1;

		$beforBack = intval( $showPage/2);

		$i = 1;
		if($currentPage<=$beforBack){
			$eitherPage = $showPage;
		}
		else{
			$eitherPage = $currentPage+$beforBack;
			$i = $currentPage-$beforBack;
		}

		if($totalPage-$currentPage<=$beforBack){
			$i = 	$totalPage - $showPage;
		}
		//Get Previous page
		if($totalPage > 1){
			if($condition_arr){
				foreach ($condition_arr as $key => $value) {
					if( $key=='start-index' ){
						$value = ($currentPage-1)*$perPage;
					}
					$query  .= '&'.$key.'='.$value;
				}
				if( $currentPage >1){
					$page[$i-2] = '<a href="?page='.($currentPage-1).$query.'">&laquo; &nbsp;&nbsp;前へ</a>';
					//Get First page
					$query = '';
					foreach ($condition_arr as $key => $value) {
						if( $key=='start-index' ){
							$value = 1;
						}
						$query  .= '&'.$key.'='.$value;
					}
					if($currentPage>$beforBack){
						$page[$i-1] = ($eitherPage>$showPage)?'<a href="?page=1'.$query.'">1</a><span class="dot">...</span>':'<a href="?page=1'.$query.'">1</a>';
						$i = $i==1?2:$i;
					}
				}
			}
			//Set link, condition in a tag.
			for($i; $i<= $eitherPage; $i++ ){
				if($i>$totalPage){
						break;
				}
				$query ='';
				if($condition_arr){
					foreach ($condition_arr as $key => $value) {
						if( $key=='start-index' ){
							$value = ($i!=1&&isset($value))? (($i-1)*$perPage)+1: 1;
						}
						$query  .= '&'.$key.'='.$value;
					}
					//$query = self::joinQuery($condition_arr);
				}
				if( $currentPage == $i ){
					$page[$i] = '<a class="active" href="?page='.$i.$query.'">'.$i .'</a>';
				}else{
					$page[$i] = '<a href="?page='.$i.$query.'">'.$i .'</a>';
				}
			}
			//Get next page
			$query='';
			if( $currentPage < $totalPage ){
				foreach ($condition_arr as $key => $value) {
					if( $key=='start-index' ){
						$value = ($currentPage)*$perPage+1;
					}
					$query  .= '&'.$key.'='.$value;
				}

				$page[$i] = (($currentPage + $beforBack)>=$totalPage)?'<a href="?page='.($currentPage+1).$query.'"> 次へ&raquo;&nbsp;&nbsp; </a>':'<span class="dot-next">...</span><a href="?page='.($currentPage+1).$query.'"> 次へ&nbsp;&nbsp;&raquo;</a>';
			}

		}
		return $page;
	}

	/**
	* Buiding param to string query
	* @author: HUYHQ
	*/
	public function buildQuery($param){
		    $tmp = array();
		    foreach($param as $key => $value){
		    	if($value!=""){
		        	$tmp [] = $key . "=" . rawurlencode($value);
		    	}
		    }
		    return join("&", $tmp);
	}


	private static function redirect4fb( $url )
    {
        echo "<script type='text/javascript'>";
        echo "window.top.location.href = '" . $url . "'";
        echo "</script>";
        exit;
    }



}
$obj = new tsActionFbYoutubeVideos();
$obj->execute();